from flask import Flask, render_template, url_for, request, redirect, make_response, session, g, send_from_directory
import pymysql

db = pymysql.connect(host="localhost", user="root", password="1234", database="terrorist")
app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'
cur = db.cursor()


@app.route('/')
def index():
    return render_template('index.html')


@app.route("/login/", methods=['GET', "POST"])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        print(username, password)
        cur.execute("select * from user where username = %s", (username))
        user = cur.fetchone()
        print(user)
        if user:
            if user[2] == password:
                session['username'] = username
                session['password'] = password
                session['user_id'] = user[0]
                return redirect(url_for('people'))
            else:
                return "密码错误"
        else:
            return "用户名不存在"


@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_pass = request.form.get('confirm_password')
        email = request.form.get('email')
        print(username, password, confirm_pass, email)
        cur.execute('select * from user where username = %s', (username))
        user = cur.fetchone()
        if user:
            return '已经注册过了'
        else:
            if password != confirm_pass:
                return '两次密码不一致'
            else:
                cur.execute('insert into user(username,password,email) values(%s,%s,%s)',
                            (username, password, email))
                db.commit()
                return redirect(url_for('login'))


@app.route('/logout/', methods=['GET', 'POST'])
def logout():
    session.clear()
    return redirect(url_for('index'))


@app.route('/time/', methods=['GET'])
def time():
    return render_template('袭击次数全球分布.html')


@app.route('/people/', methods=['GET'])
def people():
    return render_template('死亡人数全球分布.html')


@app.route('/weapon/', methods=['GET'])
def weapon():
    return render_template('武器类型词云图.html')


@app.route('/organization/')
def organization():
    return render_template('竞赛.html')


@app.route('/attack_type/')
def attack_type():
    return render_template('攻击类型词云图.html')


@app.route('/target/')
def target():
    return render_template('目标类型词云图.html')


if __name__ == '__main__':
    app.run()
